import sys

from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from qfluentwidgets import InfoBar, InfoBarPosition

from HttpApi.JsonHttpClient import JsonHttpClient
from register_page import Ui_Form
# 1. 创建一个自定义的窗口类，继承自 QWidget
class RegisterPage(QWidget, Ui_Form):
    def __init__(self):
        super().__init__()  # 调用父类的 __init__ 方法
        self.setupUi(self)  # 调用 UI 类的 setupUi 方法，设置窗口的 UI

        self.httpClient = JsonHttpClient()

        self.registerButton_2.clicked.connect(self.handle_register)
        self.goLoginButton.clicked.connect(self.go_to_login_page)


    def handle_register(self):
        # 读取name/account/password/password_2
        name = self.name.text()
        account = self.account.text()
        password = self.password.text()
        password_2 = self.password_2.text()
        # 判空
        if name == "" or account == "" or password == "" or password_2 == "":
            print("请输入完整信息")
            self.show_error_info("请输入完整信息")
            return
        # 判断两次密码是否一致
        if password != password_2:
            print("两次密码不一致")
            self.show_error_info("两次密码不一致")
            return
        print("姓名：", name)
        print("账号：", account)
        print("密码：", password)
        print("确认密码：", password_2)
        # 发送请求Post: /user/register, data: name, account, passwordHash
        post = self.httpClient.post("/user/register", {"name": name, "account": account, "passwordHash": password})
        if post["code"] == 200:
            print("注册成功")
            self.show_success_info("注册成功")
            return
        self.show_error_info(post["msg"])
        print("注册失败", post["msg"])

    def go_to_login_page(self):
        print("切换到登录页面")

    def show_success_info(self,msg):
        """显示成功信息"""
        InfoBar.success(
            title='成功',
            content=msg,
            orient=InfoBarPosition.TOP_LEFT,
            isClosable=True,
            duration=3000,
            parent=self
        )

    def show_error_info(self, msg):
        """显示错误信息"""
        InfoBar.error(
            title='失败',
            content=msg,
            orient=InfoBarPosition.TOP_LEFT,
            isClosable=True,
            duration=3000,
            parent=self
        )




# --- 程序的入口部分 ---
if __name__ == '__main__':
    # 设置应用程序高DPI缩放支持
    QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
    # 2. 创建应用程序实例
    app = QApplication(sys.argv)
    # 3. 创建我们自定义的窗口实例
    my_app_window = RegisterPage()

    # 4. 显示窗口
    my_app_window.show()

    # 5. 启动事件循环
    sys.exit(app.exec())
